import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/associated_devices/widgets/associate_unbind_devices/index.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/associate_room/index.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/widgets/button/tap_container.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class MeterInfo extends StatefulWidget {
  final Map info;
  final Function(bool value) onChange;

  const MeterInfo({super.key, required this.onChange, required this.info});

  @override
  State<StatefulWidget> createState() => _MeterInfoState();

}

class _MeterInfoState extends State<MeterInfo> {
  bool status = true;
  Map _roomInfo = {};

  Future<void> _onOffChange(int type, String onOff) async {
    EasyLoading.show();
    Map<String, dynamic> params = {"id": widget.info["electricityMeterId"], "type": type};
    await electricityMeterApi.onOffChange(params);
    EasyLoading.dismiss();
    EasyLoading.showToast("电表已${onOff == "0" ? "通电" : "断电"}");
    setState(() {
      status = onOff == "0" ? true : false;
    });
  }

  /// 获取房间信息
  void _getRoomInfo(int roomId) async {
    if (roomId != null && roomId != -1) {
      Map resData = await apartmentApi.getRoomInfo(roomId);
      print(resData);
      setState(() {
        _roomInfo = resData["data"];
      });
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void didUpdateWidget(covariant MeterInfo oldWidget) {
    setState(() {
      /* onOff: 0: 通电，1: 断电 */
      status = widget.info["onOff"] == "0" ? true : false;
    });

    if (widget.info["roomId"] != null) {
      _getRoomInfo(widget.info["roomId"]);
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [ThemeVars.boxShadow],
        color: Colors.white,
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("电表度数：${widget.info["totalKwh"]}度", style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600, ),),
                Row(
                  children: [
                    CupertinoSwitch(
                      value: status,
                      activeColor: ThemeVars.colorPrimaryDark,
                      onChanged: (value) {
                        String onOff = value ? "0" : "1";
                        int type = value ? 11 : 10;
                        _onOffChange(type, onOff);
                      },
                    ),
                    Text(status ? "通电" : "断电", style: const TextStyle(fontSize: 12, color: ThemeVars.colorTextTer),),
                  ],
                )
              ],
            ),
            const SolidDivider(padding: EdgeInsets.symmetric(vertical: 16), color: ThemeVars.colorBorder,),
            Row(
              children: [
                Text("房间电表："),
                TapContainer(
                    onTap: () {
                      Navigator.push(
                        context,
                        CupertinoPageRoute(
                          builder: (BuildContext context) {

                            return AssociatedRoom(
                              deviceId: widget.info["electricityMeterId"],
                              roomId: widget.info["roomId"] ?? -1,
                              deviceType: DeviceType.electricityMeter,
                            );
                          },
                        ),
                      ).then((hasRefresh) {
                          if (hasRefresh == true) {
                            widget.onChange(true);
                          }
                        });
                    },
                    child: widget.info["roomId"] == -1
                        ? const Text("去关联", style: TextStyle(color: ThemeVars.colorPrimary),)
                        : Text(_roomInfo["name"] ?? "", style: TextStyle(color: ThemeVars.colorPrimary),)
                ),
              ],
            ),
            const SizedBox(height: 8,),
            Row(
              children: [
                const Text("表号："),
                Text(widget.info["number"] ?? "--"),
              ],
            ),
            const SizedBox(height: 8,),
            Row(
              children: [
                const Text("状态："),
                Text(widget.info["online"] == "0" ? "在线" : "离线"),
              ],
            ),
            const SizedBox(height: 8,),
            Row(
              children: [
                const Text("更新时间："),
                Text(widget.info["onlineUpdateDate"] ?? "--"),
              ],
            )
          ],
        ),
      ),
    );
  }

}